package com.kaiwukj.android.ufamily.mvp.ui.page.active;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.TimeUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.BaseSwipeBackActivity;
import com.kaiwukj.android.ufamily.di.component.DaggerHomeV20Component;
import com.kaiwukj.android.ufamily.di.module.HomeV20Module;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.ActiveEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.requestbak.EventRequest;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ActiveResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.home.active.ActivePresenter;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.home.contract.HomeV20Contract;
import com.kaiwukj.android.ufamily.utils.BannerImageLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.youth.banner.Banner;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.EventDetail;

/**
 * @author Charles
 * @date 2019/8/28.
 * description：Kaiwu
 */
@Route(path = EventDetail)
public class ActiveDetailActivity extends BaseSwipeBackActivity<ActivePresenter> implements HomeV20Contract.ActiveView {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_active_title)
    TextView tvActiveTitle;
    //@BindView(R.id.tv_price)
    //TextView tvPrice;
    @BindView(R.id.tv_join_num)
    TextView tvJoinNum;
    @BindView(R.id.tv_max_num)
    TextView tvMaxNum;
    @BindView(R.id.tv_latest_apply_time)
    TextView tvLatestApplyTime;
    @BindView(R.id.tv_event_detail)
    TextView tvEventDetail;
    @BindView(R.id.tv_event_time)
    TextView tvEventTime;
    @BindView(R.id.tv_event_address)
    TextView tvEventAddress;
    @BindView(R.id.tv_event_contact_name)
    TextView tvEventContactName;
    @BindView(R.id.tv_event_contact_phone)
    TextView tvEventContactPhone;
    @BindView(R.id.btn_apply)
    Button btnApply;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }


    @Autowired
    int id;

    private int status;

    private boolean isJoined = false;//是否已经报名
    private int joinNum;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHomeV20Component.builder()
                .appComponent(appComponent)
                .homeV20Module(new HomeV20Module(this))
                .build().inject(this);
    }

    @Override
    public int getLayoutId() {
        ARouter.getInstance().inject(this);
        // QMUIStatusBarHelper.translucent(this);
        // QMUIStatusBarHelper.setStatusBarLightMode(this);
        return R.layout.activity_event;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvTitle.setText("活动详情");
        btnApply.setActivated(true);
        btnApply.setOnClickListener(view -> {
            EventRequest eventRequest = new EventRequest();
            eventRequest.setActivityId(id);
            if (isJoined) {
                showMessageOKCancel(this, "是否确定取消参加该活动", v -> {
                    showLoading("正在请求...");
                    mPresenter.unJoin(id);
                });
            } else {
                showMessageOKCancel(this, "是否确定参加该活动", v -> {
                    showLoading("正在请求...");
                    mPresenter.join(id);
                });

            }
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> mPresenter.fetchActiveDetail(id));
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        showLoading();
        mPresenter.fetchActiveDetail(id);
    }


    private void initActive(ActiveResult result) {

        joinNum = result.getJoinNum();

        status = result.getStatus();
        banner.setImageLoader(new BannerImageLoader());
        banner.setImages(Arrays.asList(result.getActivityImg().split(",")));
        banner.isAutoPlay(true);
        banner.start();
        tvActiveTitle.setText(result.getActivityTitle());


        int resId = 0;
        if (result.getPublisherType() == 1) {
            resId = R.mipmap.ic_active_way_flag_01;
        } else if (result.getPublisherType() == 2) {
            resId = R.mipmap.ic_active_way_flag_03;
        } else {
            resId = R.mipmap.ic_active_way_flag_02;
        }
        tvActiveTitle.setCompoundDrawablesWithIntrinsicBounds(null, null,
                ContextCompat.getDrawable(this, resId), null);

        //tvPrice.setText(String.valueOf(result.getCosts()));
        tvJoinNum.setText(String.format("已有%s人参加", result.getJoinNum()));
        tvMaxNum.setText(String.format("报名名额：%s", result.getEnrollQuota() == 0 ? "不限" : result.getEnrollQuota() + "人"));

        Date deadLineDate = TimeUtils.string2Date(result.getEnrollDeadline());


        tvLatestApplyTime.setText(String.format("截止日期：%s", TimeUtils.date2String(deadLineDate, "yyyy-MM-dd HH:mm")));
        tvEventDetail.setText(result.getActivityDetails());
        Date startDate = TimeUtils.string2Date(result.getActivityStartTime());
        Date endDate = TimeUtils.string2Date(result.getActivityEndTime());
        tvEventTime.setText(String.format("%s至%s",
                TimeUtils.date2String(startDate, "yyyy-MM-dd HH:mm"),
                TimeUtils.date2String(endDate, "yyyy-MM-dd HH:mm")));
        tvEventAddress.setText(result.getActivityAddress());
        tvEventContactName.setText(result.getContacts());
        tvEventContactPhone.setText(result.getContactNumber());
        isJoined = result.isJoined();
        refreshBtn();
    }

    private void refreshBtn() {
        if (isJoined && status != 4) {
            btnApply.setEnabled(true);
            btnApply.setBackgroundResource(R.drawable.shape_commit_gray_btn);
            btnApply.setText("取消报名");
        } else {
            btnApply.setBackgroundResource(R.drawable.selector_commit_btn);
            switch (status) {
                case 1:
                    btnApply.setEnabled(true);
                    btnApply.setText("我要报名");
                    break;
                case 2:
                    btnApply.setEnabled(false);
                    btnApply.setText("活动即将开始");
                    break;
                case 3:
                    btnApply.setEnabled(false);
                    btnApply.setText("活动正在进行中");
                    break;
                case 4:
                    btnApply.setEnabled(false);
                    btnApply.setText("活动已结束");
                    break;
            }

        }
    }

    @Override
    public void onFetchActive(@NotNull List<? extends ActiveResult> results) {

    }

    @Override
    public void onFetchActiveDetail(@NotNull ActiveResult result) {
        refreshLayout.finishRefresh();
        initActive(result);
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        hideLoading();
        switch (taskId) {
            case ActivePresenter.JOIN:
                showMessage("报名成功");
                isJoined = true;
                btnApply.setText("已报名");
                btnApply.setBackgroundResource(R.drawable.shape_commit_gray_btn);
                tvJoinNum.setText(String.format("已有%s人参加", joinNum += 1));
                EventBus.getDefault().post(new ActiveEvent(ActiveEvent.JOIN, id));
                EventBus.getDefault().post(new HomeEvent(HomeEvent.UPDATE_DATA));
                break;
            case ActivePresenter.UN_JOIN:
                showMessage("取消成功");
                isJoined = false;
                btnApply.setText("报名");
                btnApply.setBackgroundResource(R.drawable.shape_commit_btn);
                if (joinNum > 0) {
                    tvJoinNum.setText(String.format("已有%s人参加", joinNum -= 1));
                }
                EventBus.getDefault().post(new ActiveEvent(ActiveEvent.UNJOIN, id));
                EventBus.getDefault().post(new HomeEvent(HomeEvent.UPDATE_DATA));
                break;
        }
    }
}
